package email;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.mail.Header;
import javax.mail.internet.MimeUtility;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import email.core.ConfigurationProvider;
import email.core.EmailChecker;
import email.core.EmailMessage;
import email.core.EmailPoller;
import email.core.Mailbox;
import email.core.MessageListUpdater;
import email.core.EmailChecker.Protocol;

/**
 * Mailbox monitor main class
 *
 */
public class Main implements MessageListUpdater
{
	static final Logger LOGGER = Logger.getLogger(Main.class.getName());
	public static final int POLL_STEP_SECONDS = 60; 
	public static final int POLL_COLUMN_INDEX = 7;
	public static final int STATUS_COLUMN_INDEX = 5;
	public static final int MESSAGE_COUNT_COLUMN_INDEX = 6;
	//new SimpleDateFormat("dd-MMM-yyyy HH:mm:SS");
	final SimpleDateFormat dateFormat = new SimpleDateFormat(
			ConfigurationProvider.getInstance().getMessageString("messages.table.column.date.format", "dd-MMM-yyyy HH:mm:SS"));
	
	Map<TableItem, EmailPoller> pollersPerMailbox = new HashMap<TableItem, EmailPoller>();
	Map<TableItem, List<EmailMessage>> messagesPerMailbox = new HashMap<TableItem, List<EmailMessage>>();
	Table messagesListTable;
	Table mailboxListTable;
	ToolBar t;
	Shell mainShell;
	ToolItem deleteMessagesToolItem, messageInfoToolItem;
	
	void setMenu() {
		Menu menuBar = new Menu(mainShell, SWT.BAR);
		mainShell.setMenuBar(menuBar);
		
		MenuItem fileMainMenuItem = new MenuItem(menuBar, SWT.CASCADE);
		fileMainMenuItem.setText(ConfigurationProvider.getInstance().getMessageString("main.window.menu.file"));
		
		Menu fileSubMenu = new Menu(mainShell, SWT.DROP_DOWN);
		fileMainMenuItem.setMenu(fileSubMenu);
		MenuItem exitItem = new MenuItem(fileSubMenu, SWT.PUSH);
		exitItem.setText(ConfigurationProvider.getInstance().getMessageString("main.window.menu.file.exit"));
		exitItem.addListener(SWT.Selection, new Listener(){
			@Override
			public void handleEvent(Event arg0) {
				mainShell.dispose();
			}});
	}
	
	ToolBar setToolbar(Composite component) {
		t = new ToolBar(component, SWT.HORIZONTAL | SWT.NONE | SWT.FLAT);

		GridData layoutData = new GridData(GridData.FILL_HORIZONTAL);
		t.setLayoutData(layoutData);
		ToolItem ti;
		//TODO Figure out putting labels (pure non-clickable text) to the toolbar
//		ti = new ToolItem(t, SWT.NONE | SWT.FLAT | SWT.NO_FOCUS);
//		ti.setText(ConfigurationProvider.getInstance().getMessageString("toolbar.section.mailboxes.label"));
		ti = new ToolItem(t, SWT.PUSH | SWT.FLAT);
		ti.setToolTipText(ConfigurationProvider.getInstance().getMessageString("toolbar.button.refresh_mailboxes.label"));
		ti.setImage(new Image(mainShell.getDisplay(), getClass().getClassLoader().getResourceAsStream("refresh_24.png")));
		ti.addListener(SWT.Selection, new Listener(){
			@Override
			public void handleEvent(Event event) {
				mainShell.getDisplay().asyncExec(new Runnable(){
					@Override
					public void run() {
						for (TableItem tableItem : getTableSelectedOrAllItems(mailboxListTable)) {
							pollersPerMailbox.get(tableItem).checkNow(mainShell);
						}
					}
				});
			}});
		ti = new ToolItem(t, SWT.PUSH | SWT.FLAT);
		ti.setToolTipText(ConfigurationProvider.getInstance().getMessageString("toolbar.button.stop_checking.label"));
		ti.setImage(new Image(mainShell.getDisplay(), getClass().getClassLoader().getResourceAsStream("stop_24.png")));
		ti.addListener(SWT.Selection, new Listener(){
			@Override
			public void handleEvent(Event arg0) {
				mainShell.getDisplay().asyncExec(new Runnable(){
					@Override
					public void run() {
						for (TableItem tableItem : getTableSelectedOrAllItems(mailboxListTable)) {
							pollersPerMailbox.get(tableItem).stopChecker();
						}
					}});
			}});
		ti = new ToolItem(t, SWT.SEPARATOR);
		ti.setWidth(10);
		
//		ti = new ToolItem(t,  SWT.NONE | SWT.FLAT | SWT.NO_FOCUS);
//		ti.setText(ConfigurationProvider.getInstance().getMessageString("toolbar.section.messages.label"));
		deleteMessagesToolItem = new ToolItem(t, SWT.PUSH | SWT.FLAT);
		deleteMessagesToolItem.setEnabled(false);
		deleteMessagesToolItem.setImage(new Image(mainShell.getDisplay(), getClass().getClassLoader().getResourceAsStream("delete_message_24.png")));
		deleteMessagesToolItem.setToolTipText(ConfigurationProvider.getInstance().getMessageString("toolbar.button.delete_messages.label"));
		deleteMessagesToolItem.addListener(SWT.Selection, new Listener(){
			@Override
			public void handleEvent(Event arg0) {
				mainShell.getDisplay().asyncExec(new Runnable(){
					@Override
					public void run() {
						TableItem[] messageItems = messagesListTable.getSelection();
						if (messageItems.length>0) {
							List<EmailMessage> markedMessages = new ArrayList<EmailMessage>(messageItems.length);
							for (TableItem markedItem : messageItems) {
								markedMessages.add((EmailMessage)markedItem.getData());
							}
							MessageBox deleteConfirmation = new MessageBox(mainShell, SWT.ICON_QUESTION | SWT.YES | SWT.NO);
							deleteConfirmation.setText(ConfigurationProvider.getInstance().getMessageString("delete.dialog.title"));
							deleteConfirmation.setMessage(ConfigurationProvider.getInstance().getMessageString("delete.dialog.message"));
							if (deleteConfirmation.open() == SWT.NO) { return; }
							Map<EmailPoller, List<String>> pollersMap = makeDeletedUUIDsListByPooolerMap(markedMessages);
							for (EmailPoller poller : pollersMap.keySet()) {
								List<String> deleteUUIDs = pollersMap.get(poller);
								if (deleteUUIDs!=null && !deleteUUIDs.isEmpty()) {
									poller.deleteMessages(mainShell, deleteUUIDs);
								}
							}
						}
					}});
			}});
		messageInfoToolItem = new ToolItem(t, SWT.PUSH | SWT.FLAT);
		messageInfoToolItem.setEnabled(false);
		messageInfoToolItem.setImage(new Image(mainShell.getDisplay(), getClass().getClassLoader().getResourceAsStream("info_24.png")));
		messageInfoToolItem.setToolTipText(ConfigurationProvider.getInstance().getMessageString("toolbar.button.show_information.label"));
		messageInfoToolItem.addListener(SWT.Selection, new Listener(){
			@Override
			public void handleEvent(Event arg0) {
				mainShell.getDisplay().asyncExec(new Runnable(){
					@Override
					public void run() {
						TableItem[] messageItems = messagesListTable.getSelection();
						if (messageItems.length>0) {
							showMessageInfoDialog((EmailMessage)messageItems[0].getData());
						}
					}
				});
			}
		});
		return t;
	}
	
	TableItem[] getTableSelectedOrAllItems(Table t) {
		TableItem[] tableItems = t.getSelection();
		if (tableItems.length<1) {
			tableItems = t.getItems();
		}
		return tableItems;
	}
	
	Map<EmailPoller, List<String>> makeDeletedUUIDsListByPooolerMap(List<EmailMessage> markedItems) {
		Map<EmailPoller, List<String>> result = new HashMap<EmailPoller, List<String>>();
		for (TableItem mailboxItem : pollersPerMailbox.keySet()) {
			for (EmailMessage markedItem : markedItems) {
				List<EmailMessage> mailboxMessages = messagesPerMailbox.get(mailboxItem); 
				if ((mailboxMessages!=null) && (mailboxMessages.contains(markedItem))) {
					EmailPoller poller = pollersPerMailbox.get(mailboxItem);
					List<String> pollerDeleteUUIDs = result.get(poller);
					if (pollerDeleteUUIDs==null) {
						pollerDeleteUUIDs = new ArrayList<String>();
						result.put(poller, pollerDeleteUUIDs);
					}
					pollerDeleteUUIDs.add(markedItem.uuid);
				}
			}
		}
		return result;
	}
	
	void setMailboxList(Composite container) {
		mailboxListTable = new Table(container, SWT.BORDER | SWT.MULTI);

		String[] columnNames = new String[]{
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.name"),  
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.user"),   
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.host"),  
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.port"),    
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.ssl"),                
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.status_message"), 
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.message_count"), 
				ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.poll")};
		int[] columnSizes 	 = new int[]   {115,      150,		130,	  40,		  25,	               250, 	 60, 		 50};
		int[] columnFlags 	 = new int[]   {SWT.LEFT, SWT.LEFT, SWT.LEFT, SWT.RIGHT, SWT.LEFT | SWT.CHECK, SWT.LEFT, SWT.RIGHT,  SWT.RIGHT};
		TableColumn column; int columnIdx = 0;
		for (String columnName : columnNames) {
			column = new TableColumn(mailboxListTable, columnFlags[columnIdx]);
			column.setText(columnName);
			column.setWidth(columnSizes[columnIdx]);
			columnIdx++;
		}
			
		mailboxListTable.setLinesVisible(false);
		mailboxListTable.setHeaderVisible(true);
		mailboxListTable.setFont(new Font(Display.getCurrent(), mailboxListTable.getFont().getFontData()[0].getName(), 11, SWT.NORMAL));
		final int itemHeight = mailboxListTable.getFont().getFontData()[0].getHeight()+2; 
		mailboxListTable.addListener(SWT.MeasureItem, new Listener(){
			@Override
			public void handleEvent(Event event) {
				event.height = itemHeight;
			}});
		TableItem item;
		for (Mailbox mbx : ConfigurationProvider.getInstance().getMailboxList()) {
			item = new TableItem(mailboxListTable, SWT.FULL_SELECTION | SWT.BORDER);
			item.setData(mbx);
			item.setText(new String[]{mbx.alias, mbx.user, mbx.host});
			item.setText(3, mbx.port!=null?mbx.port.toString():""+EmailChecker.Protocol.valueOf(mbx.protocol).getPort());
			TableEditor editor = new TableEditor(mailboxListTable);
			Button sslButton = new Button(mailboxListTable, SWT.CHECK);
			sslButton.pack();
			editor.minimumWidth = sslButton.getSize().x;
			editor.horizontalAlignment = SWT.CENTER;
			editor.setEditor (sslButton, item, 4);
			sslButton.setEnabled(false);
			sslButton.setSelection(mbx.ssl!=null?Boolean.valueOf(mbx.ssl):Boolean.valueOf(EmailChecker.Protocol.valueOf(mbx.protocol).getSSL()));
			item.setText(STATUS_COLUMN_INDEX,"");
			item.setText(MESSAGE_COUNT_COLUMN_INDEX,"");
			item.setText(POLL_COLUMN_INDEX,""+mbx.poll+" "+ConfigurationProvider.getInstance().getMessageString("mailbox.table.column.poll.min"));
			EmailPoller poller = new EmailPoller(this.createMailChecker(mbx), this, item, mbx.poll, mainShell);
			pollersPerMailbox.put(item, poller);
			poller.checkNow(mainShell);
		}
		mailboxListTable.addSelectionListener(this.getMailboxTableSelectionListener());
	}
	
	public void onMessageList(final TableItem item, List<EmailMessage> messages) {
		Set<String> currentUids = new HashSet<String>();
		List<EmailMessage> currentMessages = messagesPerMailbox.get(item);
		if (currentMessages!=null) {
			for (EmailMessage currentMessage : currentMessages) {
				currentUids.add(currentMessage.uuid);
			}
		}
		messagesPerMailbox.put(item, messages);
		boolean showDialog = false;
		// New messages dialog is shown only when there is something new
		for (EmailMessage newMessage : messages) {
			if (!currentUids.contains(newMessage.uuid)) { showDialog = true; break; }
		}
		if (showDialog) {
			mainShell.getDisplay().asyncExec(new Runnable(){
				@Override
				public void run() {
					MessageBox notification = new MessageBox(mainShell, SWT.ICON_INFORMATION | SWT.YES);
					notification.setText(ConfigurationProvider.getInstance().getMessageString("notification.dialog.title"));
					notification.setMessage(MessageFormat.format(
							ConfigurationProvider.getInstance().getMessageString("notification.dialog.text"), 
							((Mailbox)item.getData()).alias));
					notification.open();
				}
			});
		}
		mainShell.getDisplay().asyncExec(new Runnable() {
			public void run() {
				TableItem[] selectedItems = mailboxListTable.getSelection();
				// If no item selected consider the whole list
				if (selectedItems.length<1) {
					selectedItems = mailboxListTable.getItems();
				} else {
					boolean selected = false;
					for (TableItem selectedItem : selectedItems) {
						if (selectedItem.equals(item)) { selected = true; break; }
					}
					// Don't need to update messages if the item doesn't belong to existing selection
					if (!selected) {return;}
				}
				displayMessageList(selectedItems);
			}
		});
	}
	
	void showMessageInfoDialog(EmailMessage message) {
		final Shell dialogShell = new Shell(mainShell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.ON_TOP | SWT.RESIZE);
		dialogShell.setText(ConfigurationProvider.getInstance().getMessageString("info.dialog.title"));
		dialogShell.setLayout(new GridLayout(1, true));

		
		GridData layoutData;

		Text textArea = new Text(dialogShell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY);
			layoutData = new GridData();
			layoutData.horizontalAlignment = SWT.CENTER;
			layoutData.grabExcessHorizontalSpace = true;
			layoutData.grabExcessVerticalSpace = true;
			layoutData.verticalAlignment = SWT.FILL;
			layoutData.horizontalAlignment = SWT.FILL;
			layoutData.widthHint = 400;
			layoutData.heightHint = 300;
			textArea.setLayoutData(layoutData);
			textArea.setBackground(dialogShell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
			textArea.setFont(new Font(Display.getCurrent(), textArea.getFont().getFontData()[0].getName(), 11, SWT.NORMAL));
		
		StringBuffer headers = new StringBuffer(1024);
		headers.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.mailbox")).append(message.mailbox).append("\n");
		headers.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.from")).append(message.from).append("\n");
		headers.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.to")).append(message.to).append("\n");
		headers.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.subject")).append(message.subject).append("\n");
		headers.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.date")).append(message.date).append("\n");
		headers.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.size")).append(message.size)
			.append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.size.bytes")).append("\n");
		headers.append("\n").append(ConfigurationProvider.getInstance().getMessageString("info.dialog.header.raw")).append("\n\n");
		for (Header header : message.headers) {
			headers.append(header.getName() + ": " + header.getValue()).append("\n");
		}
		textArea.setText(headers.toString());
		
		Button b = new Button(dialogShell, SWT.PUSH);
			layoutData = new GridData();
			layoutData.horizontalAlignment = SWT.CENTER;
			b.setLayoutData(layoutData);
			b.setText(ConfigurationProvider.getInstance().getMessageString("info.dialog.button.label"));
			b.addListener(SWT.Selection, new Listener(){
				@Override
				public void handleEvent(Event selection) {
					dialogShell.close();
					dialogShell.dispose();
				}});
		dialogShell.pack();
		centerDialogOnDisplay(dialogShell);
	}
	
	void centerDialogOnDisplay(Shell dialogShell) {
		dialogShell.pack();
		Rectangle display = mainShell.getDisplay().getPrimaryMonitor().getBounds();
		dialogShell.setLocation(display.x+(display.width-dialogShell.getBounds().width)/2, 
								display.y+(display.height-dialogShell.getBounds().height)/2);
		dialogShell.setActive();
		dialogShell.open();
		dialogShell.forceActive();
	}
	
	
	void displayMessageList(TableItem[] selectedItems) {
		List<EmailMessage> displayMessageList = new ArrayList<EmailMessage>();
		List<EmailMessage> mailboxMessages;
		for (TableItem item : selectedItems) {
			mailboxMessages = messagesPerMailbox.get(item);
			if (mailboxMessages!=null) {
				displayMessageList.addAll(mailboxMessages);
			}
		}
		// Display
		messagesListTable.removeAll();
		TableItem newItem;
		for (EmailMessage message : displayMessageList) {
			newItem = new TableItem(messagesListTable, SWT.BORDER | SWT.FULL_SELECTION);
			newItem.setData(message);
			newItem.setText(0, message.mailbox);
			newItem.setText(1, message.from);
			newItem.setText(2, message.to);
			newItem.setText(3, message.subject);
			newItem.setText(4, dateFormat.format(message.date));
			newItem.setText(5, ""+message.size);
		}
	}
	
	private EmailChecker createMailChecker(Mailbox mbx) {
		EmailChecker checker = new EmailChecker();
		checker.setMailboxName(mbx.alias);
		checker.setProtocol(Protocol.valueOf(mbx.protocol));
		checker.setTargetHost(mbx.host);
		checker.setTargetPort(mbx.port);
		checker.setUseSSL(mbx.ssl);
		checker.setUserName(mbx.user);
		checker.setPassword(mbx.pass);
		checker.setUseRetrHeaders(mbx.useRetrHeaders);
		return checker;
	}

	void setMessagesList(Composite container) {
		messagesListTable = new Table(container, SWT.BORDER | SWT.MULTI);

		String[] columnNames = new String[]{
				ConfigurationProvider.getInstance().getMessageString("messages.table.column.mailbox"), 
				ConfigurationProvider.getInstance().getMessageString("messages.table.column.from"),   
				ConfigurationProvider.getInstance().getMessageString("messages.table.column.to"),    
				ConfigurationProvider.getInstance().getMessageString("messages.table.column.subject"),   
				ConfigurationProvider.getInstance().getMessageString("messages.table.column.date"),    
				ConfigurationProvider.getInstance().getMessageString("messages.table.column.size")
		};
		int[] columnSizes 	 = new int[]   {115,       145,		 145,	   250,		   125,	      90};
		int[] columnFlags 	 = new int[]   {SWT.LEFT,  SWT.LEFT, SWT.LEFT, SWT.LEFT,   SWT.RIGHT, SWT.RIGHT};
		TableColumn column; int columnIdx = 0;
		for (String columnName : columnNames) {
			column = new TableColumn(messagesListTable, columnFlags[columnIdx]);
			column.setText(columnName);
			column.setWidth(columnSizes[columnIdx]);
			columnIdx++;
		}
		
		messagesListTable.setLinesVisible(false);
		messagesListTable.setHeaderVisible(true);
		messagesListTable.setFont(new Font(Display.getCurrent(), messagesListTable.getFont().getFontData()[0].getName(), 11, SWT.NORMAL));
		final int itemHeight = messagesListTable.getFont().getFontData()[0].getHeight()+6; 
		messagesListTable.addListener(SWT.MeasureItem, new Listener(){
			@Override
			public void handleEvent(Event event) {
				event.height = itemHeight;
			}});
		messagesListTable.addSelectionListener(getMessagesTableSelectionListener());
	} 
	
	SelectionListener getMessagesTableSelectionListener() {
		return new SelectionListener() {
			@Override
			public void widgetDefaultSelected(SelectionEvent event) {
				this.processSelection((Table)event.getSource());
			}

			@Override
			public void widgetSelected(SelectionEvent event) {
				this.processSelection((Table)event.getSource());
			}
			
			void processSelection(Table t) {
				if (t.getSelectionCount()<1) {
					// Disable buttons
					deleteMessagesToolItem.setEnabled(false);
					messageInfoToolItem.setEnabled(false);
				} else {
					// Enable buttons
					deleteMessagesToolItem.setEnabled(true);
					if (t.getSelectionCount()==1) { messageInfoToolItem.setEnabled(true); } 
					else { messageInfoToolItem.setEnabled(false); }
				}
			}
		};
	}
	
	SelectionListener getMailboxTableSelectionListener() {
		return new SelectionListener() {
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				this.processSelection();
			}

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				this.processSelection();
			}
			
			void processSelection() {
				mainShell.getDisplay().syncExec(new Runnable(){
					@Override
					public void run() {
						TableItem[] selectedItems = mailboxListTable.getSelection();
						if (selectedItems.length<1) { selectedItems = mailboxListTable.getItems(); }
						displayMessageList(selectedItems);
					}
				});
			}
		};
	}
	
	void populateMainWindow() {
		this.setMenu();
		mainShell.setText(ConfigurationProvider.getInstance().getMessageString("main.window.title"));
		mainShell.setLayout(new GridLayout(1, true));
		this.setToolbar(mainShell);
		
		//TODO Verify the necessity of the sashform's parent composite w/FillLayout/FILL_BOTH
		SashForm sashForm = new SashForm(mainShell, SWT.VERTICAL);
		sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
		sashForm.setBackground(mainShell.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
		
		this.setMailboxList(sashForm);
		this.setMessagesList(sashForm);
		sashForm.setWeights(new int[]{1,2});
	}
	
	void showMainWindow() {
    	Display display = new Display ();
    	mainShell = new Shell(display);
    	this.populateMainWindow();
    	mainShell.open();
    	mainShell.setMinimized(true);
    	//TODO: use the following when system tray is supported
    	//mainShell.setVisible(false);
    	while (!mainShell.isDisposed()) {
    		if (!display.readAndDispatch()) display.sleep();
    	}
    	display.dispose();
    	// Now stop all polling threads
    	for (EmailPoller poller : this.pollersPerMailbox.values()) {
    		poller.stopPolling();
    	}
	}
	
	public interface MessageListUpdater {
		public void onMessageList(TableItem item, List<EmailMessage> messages);
	}
	
	String decodeText(String original) {
		String result = original;
    	try {
			result = MimeUtility.decodeText(original);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
    public static void main( String[] args ) {
    	if (args.length>0) {
    		ConfigurationProvider.getInstance().setConfigurationLocation(args[0]);
    	}
    	if (args.length>1) {
    		ConfigurationProvider.getInstance().setMessagesLocation(args[1]);
    	}
    	new Main().showMainWindow();
    }
}
